<?php

namespace app\service\shop;

use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 商城登陆
 * User : Du
 * Date : 2022/11/27
 * Time : 15:36
 * Class LoginServices
 * @package projects\services\shop
 */
class LoginServices
{

    /**
     * 用户登陆
     * User : Du
     * Date : 2022/11/27
     * Time : 19:30
     * @param array $request
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function userLogin(array $request)
    {
        $res = Common::getData(UserTable, ['mobile' => $request['mobile']], ['id', 'user_name', 'password', 'mobile']);
        if (!$res || !password_verify($request['password'], $res['password'])) {
            return '账户不存在或密码错误';
        }
        session('shop_user_data', $res);
        return true;
    }

    /**
     * 用户注册
     * User : Du
     * Date : 2022/11/27
     * Time : 16:55
     * @param array $request
     * @return string|bool
     */
    public static function userRegister(array $request)
    {
        if (Common::getValue(UserTable, ['mobile' => $request['mobile']], 'id')) {
            return '手机号已注册';
        }
        $password = password_hash($request['password'], PASSWORD_BCRYPT);
        $data = [
            'user_name' => $request['username'],
            'password' => $password,
            'mobile' => $request['mobile'],
        ];
        $id = Common::addData(UserTable, $data, true);
        $data['id'] = $id;
        session('shop_user_data', $data);
        return true;
    }
}